<?php 
require_once 'Blogg.php';
require_once ('./common/Validation.php');
class BloggList
{
	private $database = null;
	const TO_LONG = 0;
	const TITLE_USED = 1;
	const POST_PASSED = 2;
	const POST_FAILED = 3;
	/*public function __construct($database)
	{
		$this->database = $database; 
	}
	*/
	//TODO:: Skapa en konstruktor som tar en databas
	public function getAllPosts(Database $db)
	{
		$sql = "SELECT * FROM posts";
		$stmt = $db -> Select($sql);
		
		if ($stmt->bind_result($postId, $date, $title, $post) == FALSE)
		{
			throw new Exception($this->mysqli->error);
		} 
		
		$stmt->bind_result($postId, $date, $title, $post);
		
		$array = new BloggArray();
		
		while ($stmt->fetch())
		{
			$blogg = new Blogg($postId, $date, $title, $post);
			$array->add($blogg);
		}
		
		$stmt->close();
		
		return $array;
	} 
	
	public function getPostByID($postId, Database $db) {
		
		$sql = "Select * FROM posts Where postId = ?";
		$stmt = $db->Prepare($sql);
		$stmt -> bind_param("i", $postId);
		// ska ske i databass klassen
		$stmt->execute();
		if ($stmt->bind_result($postId, $date, $title, $post) == FALSE)
		{
			throw new Exception($this->mysqli->error);
		}
		if ($stmt->fetch()) 
		{
		 	$ret = new Blogg($postId, $date, $title, $post);
		} 
		else{
			throw new Exception("could not find a post with id $postId");
		}
		$stmt->close();
		return $ret;
	}
	public function PostNewPost($title, $post, Database $db)
	{

		if (isset($title) && isset($post))
		{
			if($stmt = $db->Prepare('SELECT * FROM posts Where title=?'))
			{
				$stmt->bind_param('s',$title);
				$stmt->execute();
				$stmt->bind_result($postId, $date, $title, $post);
				while($stmt->fetch())
				{
					if ($title == $title)
					{
						$stmt->close();
						return self::TITLE_USED;
					}
				}
				$stmt->close();
			}
			$vali = new Validation();
			if($vali->filterJavascript($title,$post))
			{
				if ($stmt = $db->Prepare('INSERT INTO posts (title, post) VALUES (?,?)'))
				{
					$stmt->bind_param('ss', $title, $post);
					$stmt->execute();
					$stmt->close();
					return self::POST_PASSED;
				}
				else{
					return self::POST_FAILED;
				}
			}
		}
	}

	public function DeletePost ($title)
	{
		if (isset ($title))
		{
			if($stmt = $this->database->Prepare('DELETE FROM post WHERE title = ?'))
			{
				$stmt->bind_param('s', $title);
				$stmt->execute();
				$stmt->close();
				return true;
			}
		}
		return false;
	}
} 
